package com.byd.model;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import com.byd.utils.Lg;

public final class MyThreadPool {
	private static ExecutorService mInternetExecutors;
	private static ExecutorService mPictureExecutors;
	private static ExecutorService mIOExecutors;
	private static ExecutorService mComputeExecutors;

	public static void release() {
		Lg.i("release");
		shutdown(mInternetExecutors);
		shutdown(mPictureExecutors);
		shutdown(mIOExecutors);
		shutdown(mComputeExecutors);
	}

	private static void shutdown(ExecutorService pool) {
		try {
			if(pool != null) {
				pool.shutdown();
			}
		}
		catch (final Exception e) {
			Lg.printStackTrace(e);
		}
	}

	public static synchronized ExecutorService getInternetExecutors() {
		if(mInternetExecutors == null || mInternetExecutors.isShutdown()) {
			mInternetExecutors = Executors.newFixedThreadPool(3, new ThreadFactory() {
				@Override
				public Thread newThread(Runnable r) {
					return new MyThread("IntTd", r);
				}
			});
		}
		return mInternetExecutors;
	}

	public static synchronized ExecutorService getPictureExecutors() {
		if(mPictureExecutors == null || mPictureExecutors.isShutdown()) {
			mPictureExecutors = Executors.newFixedThreadPool(3, new ThreadFactory() {
				@Override
				public Thread newThread(Runnable r) {
					return new MyThread("PicTd", r);
				}
			});
		}
		return mPictureExecutors;
	}

	public static synchronized ExecutorService getIOExecutors() {
		if(mIOExecutors == null || mIOExecutors.isShutdown()) {
			mIOExecutors = Executors.newFixedThreadPool(3, new ThreadFactory() {
				@Override
				public Thread newThread(Runnable r) {
					return new MyThread("IOTd", r);
				}
			});
		}
		return mIOExecutors;
	}

	public static synchronized ExecutorService getComputeExecutors() {
		if(mComputeExecutors == null || mComputeExecutors.isShutdown()) {
			mComputeExecutors = Executors.newFixedThreadPool(3, new ThreadFactory() {
				@Override
				public Thread newThread(Runnable r) {
					return new MyThread("ComTd", r);
				}
			});
		}
		return mComputeExecutors;
	}

	public static MyThread postNewThread(String name, Runnable action) {
		final MyThread thread = new MyThread(name, action);
		thread.start();
		return thread;
	}
}
